import 'package:flutter/material.dart';

///zhudaihao
///2024-1-30
///带进度条登录按钮
class ProgressButton extends StatefulWidget {
  ///按钮文本
  final String? text;

  ///按钮背景颜色
  final Color? backColor;

  ///按钮点击回调
  final Function? onFinish;

  const ProgressButton({Key? key, this.text, this.backColor, this.onFinish})
      : super(key: key);

  @override
  State<ProgressButton> createState() => _ProgressButtonState();
}

class _ProgressButtonState extends State<ProgressButton> {
  ButtonState _buttonState = ButtonState.none;

  @override
  Widget build(BuildContext context) {
    return MaterialButton(
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(50)),
        minWidth: 240,
        height: 50,
        color: widget.backColor ?? Colors.blue,
        child: BuildChild(
          text: widget.text ?? "",
          buttonState: _buttonState,
        ),
        onPressed: () {
          setState(() {
            _buttonState = ButtonState.loading;
            Future.delayed(const Duration(milliseconds: 2000), () {
              setState(() {
                _buttonState = ButtonState.done;
                if (widget.onFinish != null) {
                  widget.onFinish!();
                }
              });
            });
          });
        });
  }
}

///按钮状态值
enum ButtonState { none, loading, done }

///不同状态对应的widget
class BuildChild extends StatelessWidget {
  final ButtonState? buttonState;
  final String? text;

  const BuildChild({Key? key, required this.buttonState, this.text})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    Widget? child = Container();
    if (buttonState == ButtonState.none) {
      child = Text(
        text!,
        style: const TextStyle(color: Colors.white, fontSize: 20),
      );
    }

    if (buttonState == ButtonState.loading) {
      child = const CircularProgressIndicator(
        color: Colors.white,
        strokeWidth: 2,
      );
    }

    if (buttonState == ButtonState.done) {
      child = const Icon(
        Icons.done,
        color: Colors.white,
      );
    }

    return child;
  }
}
